// 全局变量
let detailItems = [];
let selectedDetailItems = [];
let selectedGoodsItems = [];

$(document).ready(function () {
    let detailItems = [];
    let reviewNo = getUrlParameter('reviewNo');
    let isEditMode = !!reviewNo;

    // 初始化页面
    initPage();

    function initPage() {
        if (isEditMode) {
            loadInventoryData();
        }
        bindEvents();
        renderDetailTable();
        updateSummary();
    }

    function bindEvents() {
        // 保存按钮
        $('#saveBtn').click(function () {
            saveInventory();
        });

        // 添加货品按钮
        $('#addGoodsBtn').click(function () {
            showAddGoodsModal();
        });

        // 删除选中项按钮
        $('#deleteSelectedBtn').click(function () {
            deleteSelectedItems();
        });

        // 导入按钮
        $('#importBtn').click(function () {
            importData();
        });

        // 保存货品按钮
        $('#saveGoodsBtn').click(function () {
            addGoodsToDetail();
        });
    }

    function loadInventoryData() {
        if (!reviewNo) return;

        // 获取盘点主表数据
        $.ajax({
            url: `/api/app/review-services/get-inventory-by-sheet-no-async`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ reviewNo: reviewNo }),
            success: function (response) {
                if (response.code === 200) {
                    const data = response.resultData;
                    $('#reviewNo').val(data.reviewNo);
                    $('#reviewType').val(data.reviewType);
                    $('#warehouseId').val(data.warehouseid);
                    $('#startTime').val(formatDateTimeLocal(data.startTime));
                    $('#endTime').val(formatDateTimeLocal(data.endTime));
                    $('#remark').val(data.remark);
                    
                    // 加载明细数据
                    loadDetailItems();
                } else {
                    showError('加载数据失败：' + response.message);
                }
            },
            error: function (xhr, status, error) {
                showError('加载数据失败：' + error);
            }
        });
    }

    function loadDetailItems() {
        if (!reviewNo) return;

        const pageData = {
            pageIndex: 1,
            pageSize: 1000,
            keyword: reviewNo
        };

        $.ajax({
            url: '/api/app/detail-services/get-detail-page',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(pageData),
            success: function (response) {
                if (response.code === 200) {
                    detailItems = response.resultData || [];
                    renderDetailTable();
                    updateSummary();
                } else {
                    showError('加载明细数据失败：' + response.message);
                }
            },
            error: function (xhr, status, error) {
                showError('加载明细数据失败：' + error);
            }
        });
    }

    function renderDetailTable() {
        const tbody = $('#detailTable tbody');
        tbody.empty();

        if (detailItems.length === 0) {
            tbody.append('<tr><td colspan="12" class="text-center">暂无数据</td></tr>');
            return;
        }

        detailItems.forEach(function (item, index) {
            const row = `
                <tr>
                    <td><input type="checkbox" class="item-checkbox" value="${index}"></td>
                    <td>${item.goodscodeNo || ''}</td>
                    <td>${item.goodscodeName || ''}</td>
                    <td>${formatNumber(item.rqty)}</td>
                    <td>${formatNumber(item.ramout)}</td>
                    <td>
                        <input type="number" class="form-control form-control-sm counted-qty" 
                               value="${item.pqty || 0}" 
                               data-index="${index}"
                               onchange="updateCountedQty(this)">
                    </td>
                    <td>${item.unit || ''}</td>
                    <td class="${item.dqty > 0 ? 'text-success' : item.dqty < 0 ? 'text-danger' : ''}">
                        ${formatNumber(item.dqty)}
                    </td>
                    <td class="${item.damount > 0 ? 'text-success' : item.damount < 0 ? 'text-danger' : ''}">
                        ${formatNumber(item.damount)}
                    </td>
                    <td>${getDetailStatusText(item.dstatus)}</td>
                    <td>${formatNumber(item.dprice)}</td>
                    <td>
                        <button class="btn btn-sm btn-danger" onclick="removeDetailItem(${index})">删除</button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    function updateSummary() {
        let totalRqty = 0;
        let totalRamout = 0;
        let totalPqty = 0;
        let totalDqty = 0;
        let totalDamount = 0;

        detailItems.forEach(function (item) {
            totalRqty += parseFloat(item.rqty || 0);
            totalRamout += parseFloat(item.ramout || 0);
            totalPqty += parseFloat(item.pqty || 0);
            totalDqty += parseFloat(item.dqty || 0);
            totalDamount += parseFloat(item.damount || 0);
        });

        $('#totalRqty').text(formatNumber(totalRqty));
        $('#totalRamout').text(formatNumber(totalRamout));
        $('#totalPqty').text(formatNumber(totalPqty));
        $('#totalDqty').text(formatNumber(totalDqty));
        $('#totalDamount').text(formatNumber(totalDamount));
    }

    function saveInventory() {
        const formData = {
            reviewNo: $('#reviewNo').val(),
            reviewType: $('#reviewType').val(),
            warehouseid: $('#warehouseId').val(),
            startTime: $('#startTime').val(),
            endTime: $('#endTime').val(),
            userId: getCurrentUserId(),
            remark: $('#remark').val(),
            rstauts: 1
        };

        // 验证必填字段
        if (!formData.reviewType || !formData.startTime || !formData.endTime || !formData.warehouseid) {
            showWarning('请填写必填字段');
            return;
        }

        const url = isEditMode ? '/api/app/review-services/update-review' : '/api/app/review-services/add-review';

        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function (response) {
                if (response.code === 200) {
                    // 保存明细数据
                    saveDetailItems();
                } else {
                    showError('保存失败：' + response.message);
                }
            },
            error: function (xhr, status, error) {
                showError('保存失败：' + error);
            }
        });
    }

    function saveDetailItems() {
        if (detailItems.length === 0) {
            showSuccess('保存成功');
            return;
        }

        const promises = detailItems.map(item => {
            const detailData = {
                reviewNo: $('#reviewNo').val(),
                goodscodeNo: item.goodscodeNo,
                goodscodeName: item.goodscodeName,
                rqty: item.rqty,
                ramout: item.ramout,
                pqty: item.pqty,
                unit: item.unit,
                dqty: item.dqty,
                damount: item.damount,
                dstatus: item.dstatus,
                dprice: item.dprice,
                dremark: item.dremark
            };

            return $.ajax({
                url: '/api/app/detail-services/add-detail',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(detailData)
            });
        });

        Promise.all(promises).then(function () {
            showSuccess('保存成功');
        }).catch(function (error) {
            showError('保存明细失败：' + error);
        });
    }

    function showAddGoodsModal() {
        $('#goodsModal .modal-title').text('添加货品');
        $('#goodsModal').modal('show');
        $('#goodsForm')[0].reset();
    }

    function addGoodsToDetail() {
        const goodsData = {
            goodscodeNo: $('#modalGoodscodeNo').val(),
            goodscodeName: $('#modalGoodscodeName').val(),
            rqty: parseFloat($('#modalRqty').val()) || 0,
            ramout: parseFloat($('#modalRamout').val()) || 0,
            pqty: 0,
            unit: $('#modalUnit').val(),
            dqty: 0,
            damount: 0,
            dstatus: 1,
            dprice: parseFloat($('#modalDprice').val()) || 0,
            dremark: $('#modalDremark').val()
        };

        // 验证必填字段
        if (!goodsData.goodscodeNo || !goodsData.goodscodeName) {
            showWarning('请填写货品编码和名称');
            return;
        }

        detailItems.push(goodsData);
        renderDetailTable();
        updateSummary();
        $('#goodsModal').modal('hide');
        showSuccess('添加货品成功');
    }

    function deleteSelectedItems() {
        const selectedIndexes = [];
        $('.item-checkbox:checked').each(function () {
            selectedIndexes.push(parseInt($(this).val()));
        });

        if (selectedIndexes.length === 0) {
            showWarning('请选择要删除的项目');
            return;
        }

        if (confirm('确定要删除选中的项目吗？')) {
            // 从大到小删除，避免索引变化
            selectedIndexes.sort((a, b) => b - a).forEach(index => {
                detailItems.splice(index, 1);
            });
            renderDetailTable();
            updateSummary();
            showSuccess('删除成功');
        }
    }

    function importData() {
        showInfo('导入功能开发中...');
    }

    // 工具函数
    function formatNumber(num) {
        if (num === null || num === undefined) return '0.00';
        return parseFloat(num).toFixed(2);
    }

    function formatDateTimeLocal(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}`;
    }

    function getDetailStatusText(status) {
        const statusMap = {
            1: '待盘点',
            2: '已盘点',
            3: '有盈亏',
            4: '无盈亏'
        };
        return statusMap[status] || '未知';
    }

    function getUrlParameter(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }

    function getCurrentUserId() {
        return '00000000-0000-0000-0000-000000000001';
    }

    function showSuccess(message) {
        alert('成功：' + message);
    }

    function showError(message) {
        alert('错误：' + message);
    }

    function showWarning(message) {
        alert('警告：' + message);
    }

    function showInfo(message) {
        alert('信息：' + message);
    }
});

// 全局函数，供HTML调用
function updateCountedQty(input) {
    const index = parseInt($(input).data('index'));
    const countedQty = parseFloat($(input).val()) || 0;
    
    if (index >= 0 && index < window.detailItems.length) {
        const item = window.detailItems[index];
        item.pqty = countedQty;
        item.dqty = countedQty - parseFloat(item.rqty || 0);
        item.damount = item.dqty * parseFloat(item.dprice || 0);
        
        // 重新渲染表格和汇总
        renderDetailTable();
        updateSummary();
    }
}

function removeDetailItem(index) {
    if (confirm('确定要删除这个货品吗？')) {
        window.detailItems.splice(index, 1);
        renderDetailTable();
        updateSummary();
        alert('删除成功');
    }
}

// 暴露给全局使用
window.detailItems = [];
window.renderDetailTable = function() {
    const tbody = $('#detailTable tbody');
    tbody.empty();

    if (window.detailItems.length === 0) {
        tbody.append('<tr><td colspan="12" class="text-center">暂无数据</td></tr>');
        return;
    }

    window.detailItems.forEach(function (item, index) {
        const row = `
            <tr>
                <td><input type="checkbox" class="item-checkbox" value="${index}"></td>
                <td>${item.goodscodeNo || ''}</td>
                <td>${item.goodscodeName || ''}</td>
                <td>${formatNumber(item.rqty)}</td>
                <td>${formatNumber(item.ramout)}</td>
                <td>
                    <input type="number" class="form-control form-control-sm counted-qty" 
                           value="${item.pqty || 0}" 
                           data-index="${index}"
                           onchange="updateCountedQty(this)">
                </td>
                <td>${item.unit || ''}</td>
                <td class="${item.dqty > 0 ? 'text-success' : item.dqty < 0 ? 'text-danger' : ''}">
                    ${formatNumber(item.dqty)}
                </td>
                <td class="${item.damount > 0 ? 'text-success' : item.damount < 0 ? 'text-danger' : ''}">
                    ${formatNumber(item.damount)}
                </td>
                <td>${getDetailStatusText(item.dstatus)}</td>
                <td>${formatNumber(item.dprice)}</td>
                <td>
                    <button class="btn btn-sm btn-danger" onclick="removeDetailItem(${index})">删除</button>
                </td>
            </tr>
        `;
        tbody.append(row);
    });
};

window.updateSummary = function() {
    let totalRqty = 0;
    let totalRamout = 0;
    let totalPqty = 0;
    let totalDqty = 0;
    let totalDamount = 0;

    window.detailItems.forEach(function (item) {
        totalRqty += parseFloat(item.rqty || 0);
        totalRamout += parseFloat(item.ramout || 0);
        totalPqty += parseFloat(item.pqty || 0);
        totalDqty += parseFloat(item.dqty || 0);
        totalDamount += parseFloat(item.damount || 0);
    });

    $('#totalRqty').text(formatNumber(totalRqty));
    $('#totalRamout').text(formatNumber(totalRamout));
    $('#totalPqty').text(formatNumber(totalPqty));
    $('#totalDqty').text(formatNumber(totalDqty));
    $('#totalDamount').text(formatNumber(totalDamount));
};

function formatNumber(num) {
    if (num === null || num === undefined) return '0.00';
    return parseFloat(num).toFixed(2);
}

function getDetailStatusText(status) {
    const statusMap = {
        1: '待盘点',
        2: '已盘点',
        3: '有盈亏',
        4: '无盈亏'
    };
    return statusMap[status] || '未知';
} 